package com.child.util;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.child.java.pojo.UsersInfo;

/*
 * Web层处理的工具类
 */
public class WebUtils {

	
	/**
	 * 检查用户是否登陆
	 * @param request
	 * @param response
	 * @return
	 */
	public static UsersInfo checkUser(HttpServletRequest request, HttpServletResponse response) {
		UsersInfo user = null;
		user = (UsersInfo) request.getSession().getAttribute("user");
		if (user == null) {
			Cookie[] cookies = request.getCookies();
			if (cookies != null && cookies.length > 0) {
				for (Cookie c : cookies) {
					String name = c.getName();
					if ("user".equals(name)) {
						String value = c.getValue();
						String[] namePassword = value.split(",");
						user = new UsersInfo(namePassword[0], namePassword[1], namePassword[2]);
						request.getSession().setAttribute("user", user);
						break;
					}
				}
			}
		}
		return user;
	}

	/**
	 * 登陆
	 * @param request
	 * @param response
	 * @param user
	 * @param auto
	 */
	public static void login(HttpServletRequest request, HttpServletResponse response, UsersInfo user, boolean auto) {
		HttpSession session = request.getSession();
		session.setAttribute("user", user);

		if (auto) {
			Cookie c = new Cookie("user", user.getId() + "," + user.getUsername() + "," + user.getPassword());
			c.setMaxAge(60 * 60 * 24 * 30);
			c.setPath("/");
			response.addCookie(c);
		}
	}

	/**
	 * 登出
	 * @param request
	 * @param response
	 */
	public static void logout(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		Cookie c = new Cookie("user", "");
		c.setMaxAge(0);
		c.setPath("/");
		response.addCookie(c);
	}

	/**
	 * 得到浏览过的所有图书
	 * @param request
	 * @return
	 */
	public static List<Map<String, String>> getHistoryBooks(HttpServletRequest request) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Cookie[] cs = request.getCookies();
		if(cs!=null && cs.length>0) {
			for(int i=cs.length-1;i>=0;i--) {
				Cookie c = cs[i];
				String cName = c.getName();
				if(cName.startsWith("book_")) {
					String id = cName.substring(cName.indexOf("_")+1);
					String name = URLDecoder.decode(c.getValue());
					HashMap<String, String> map = new HashMap<String,String>();
					map.put("id", id);
					map.put("name", name);
					list.add(map);
				}
			}
		}
		return list;
	}

	/**
	 * 清空浏览历史
	 * @param request
	 * @param resp
	 */
	public static void clearHistory(HttpServletRequest request, HttpServletResponse resp) {
		Cookie[] cs = request.getCookies();
		if(cs!=null && cs.length>0) {
			for(int i=cs.length-1;i>=0;i--) {
				Cookie c = cs[i];
				String cName = c.getName();
				if(cName.startsWith("book_")) {
					c.setMaxAge(0);
					resp.addCookie(c);
				}
			}
		}
	}
	
	/*
	 * 生成订单号,订单号的组成 两位年+两位月+两位日+两位小时+当天的订单总数 如:11071012100
	 * 
	 * @param count
	 * 
	 * @return
	 */
	public static String buildOrderid(long count) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHH");// 2011-07-10
		StringBuilder out = new StringBuilder(dateFormat.format(new Date()));
		int length = 15;
		int countLength = String.valueOf(out).length();
		int zeroLength = length - countLength;
		for (int i = 0; i < zeroLength; i++) {
			out.append(0);
		}
		out.append(count);
		return out.toString();
	}
	/**
	 * 上传图书图片
	 * @param request
	 * @return
	 *//*
	public static BooksInfo uploadBook(HttpServletRequest request) {
		BooksInfo book = new BooksInfo();

		String id = UUID.randomUUID().toString();
		book.setId(id);

		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List<FileItem> fileItems = upload.parseRequest(request);
			for (FileItem item : fileItems) {
				// 判断是否为普通表单字段
				if (item.isFormField()) {
					// 封装bean
					BeanUtils.setProperty(book, item.getFieldName(), item.getString("utf-8"));
				} else {
					// 文件上传字段
					// 获得文件名 文件名有可能有中文 和麻烦， 所以我们采取自定义文件名， 保证不重复
					String filename = item.getName();
					String extName = filename.substring(filename.lastIndexOf("."));
					filename = id + extName;

					// 获得相对当前web应用的路径
					String webPath = "/img/" + filename;
					// 获得绝对路径
					ServletContext servletContext = request.getSession().getServletContext();
					String path = servletContext.getRealPath(webPath);
					// 创建文件
					File file = new File(path);
					file.getParentFile().mkdirs();
					file.createNewFile();

					// 创建流对拷
					InputStream in = item.getInputStream();
					OutputStream out = new FileOutputStream(file);
					Streams.copy(in, out, true);

					// 删除临时文件
					item.delete();

					// 文件路径 封装到bean 的 imagepath
					BeanUtils.setProperty(book, "imagepath", webPath);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return book;
	}*/
}
